# -*- coding: utf-8 -*-
"""
@File    : justdoo_param
@Author  : Lucas
@Date    : 2024-08-19 17:17:59
@Description: 系统参数 ir_config.parameter在新建修改删除参数时会清理缓存，
              故添加此参数用作自动化任务以及其他操作时的参数变更和管控
"""

import logging
from odoo import api, fields, models

_logger = logging.getLogger(__name__)


class SystemParameter(models.Model):
    _log_access = False
    _name = 'justdoo.system.param'
    _description = '内部参数'
    _rec_name = 'key'

    key = fields.Char(string='参数名', required=True)
    value = fields.Text(string='参数值', required=True)
    param_note = fields.Text(string='参数说明')

    _sql_constraints = [('key_uniq', 'unique (key)', '参数名已使用，请不要重复使用')]

    @api.model
    def get_param(self, key, default=False):
        # self.check_access_rights('read')
        self.check_access('read')
        temp_param = self.env['justdoo.system.param'].sudo().search([('key', '=', key)], limit=1)
        if not temp_param:
            return default
        return temp_param.value or default

    @api.model
    def set_param(self, key, value):
        param = self.sudo().search([('key', '=', key)], limit=1)
        if param and (value is False or value is None):
            old_value = param.value
            param.sudo().unlink()
            return old_value
        if not param:
            self.sudo().create({'key': key, 'value': value})
            return False
        old_value = param.value
        if str(value) != old_value:
            param.sudo().write({'value': value})
        return old_value



